<template>
  <a-upload
    :file-list="fileList"
    :before-upload="beforeUpload"
    @remove="handleRemove"
    :accept="props.accept || '*'"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      选择附件
    </a-button>
  </a-upload>
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, watch } from "vue";
import _ from "lodash";

const { proxy } = getCurrentInstance();
const props = defineProps({ files: Array, accept: String });
const emit = defineEmits(["update:files"]);

const fileList = ref([]);
// 首次挂载
onMounted(() => {
  fileList.value = (props.files || []).map((o, i) => {
    // 要求file为{name,id}
    if (o instanceof Object) {
      return { uid: i, url: o.url, name: o.name, id: o.id };
    }
  });
});

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

const beforeUpload = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    proxy.$message.error("文件大小不能超过20MB!");
  }
  if (isLt20M) {
    fileList.value = [...fileList.value, file];
  }
  return false;
};

watch(
  () => fileList.value,
  (v) => {
    emit("update:files", v);
  }
);
</script>

<style lang="less" scoped></style>
